package cn.edu.sjtu.process_management.controller;

import cn.edu.sjtu.process_management.model.Result;
import cn.edu.sjtu.process_management.model.User;
import cn.edu.sjtu.process_management.service.MessageService;
import cn.edu.sjtu.process_management.util.ResultUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MessageController {
    @Autowired
    private MessageService messageService;
    private static int managerRole = 1;

    /*传递消息*/
    @RequestMapping(value = "/process/message", method = RequestMethod.POST)
    public Result messageSend(@RequestBody String string) {
        JSONObject jsonObject = JSON.parseObject(string);
        String userId = jsonObject.getObject("from", String.class);
        User user = messageService.getUserByUserId(userId);
        String ecnId = jsonObject.getObject("ecnId", String.class);
        JSONArray toUser = messageService.getUserByECN(ecnId);
        JSONObject message = jsonObject.getJSONObject("message");
        messageService.sendMessage(user, toUser, message);
        return ResultUtil.success();
    }

    /*操作人员发送消息给全体管理人员*/
    @RequestMapping(value = "/process/messageToManager", method = RequestMethod.POST)
    public Result messageToManager(@RequestBody String string) {
        JSONObject jsonObject = JSON.parseObject(string);
        String userId = jsonObject.getObject("from", String.class);
        User user = messageService.getUserByUserId(userId);
        //查询所有管理人员
        JSONArray toUser = messageService.getUserByRole(managerRole);
        JSONObject message = jsonObject.getJSONObject("message");
        messageService.sendMessage(user, toUser, message);
        return ResultUtil.success();
    }
}
